package edu.biwu.response;/**
 * @author 王俊彪
 * @version 1.0
 */

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;

@WebServlet("/resp/demo05")
public class ResponseDemo05 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取字节输出流，并且应用缓冲流
        ServletOutputStream os = response.getOutputStream();//字节流的父类
        BufferedOutputStream bos = new BufferedOutputStream(os);
        //告诉浏览器，要响应的是一张图片
        String fileName = request.getParameter("fileName");
        String mimeType = this.getServletContext().getMimeType(fileName);
        System.out.println(fileName);
        System.out.println(mimeType);
        //设置响应头,目的是告诉浏览器，我即将给你响应的类型
        response.setHeader("Content-Type",mimeType);
//        response.setContentType(mimeType);
        InputStream is = getServletContext().getResourceAsStream("/1.jpg");
        BufferedInputStream bis = new BufferedInputStream(is);
        int b;
        while((b=bis.read())!=-1){
            bos.write(b);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
